import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import autoprefixer from 'autoprefixer'
import pxtoviewport from 'postcss-px-to-viewport'

// https://vite.dev/config/
export default ({ mode }) => {
  return defineConfig({
    plugins: [
      vue(),
      vueJsx(),
      Components({
        resolvers: [VantResolver({ importStyle: false })]
      }),
      vueDevTools()
    ],
    css: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtoviewport({
            viewportWidth: 375
          })
        ]
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0',
      port: 5173, // 端口号
      open: false, // 是否自动打开浏览器
      proxy: {
        '^/api': {
          target: loadEnv(mode, process.cwd()).VITE_API_URL,
          changeOrigin: true
          // rewrite: (path) => path.replace(/^\/disease/, '')
        }
      }
    },
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            } else {
              return null
            }
          }
        }
      }
    }
  })
}
